package com.fubowen.lepton.ui.container.children.download

import android.os.Bundle
import android.os.Environment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.SortedList
import com.fubowen.lepton.conf.FileConfig
import com.fubowen.lepton.conf.SiteConfigViewModel
import com.fubowen.lepton.databinding.FragmentDownloadBinding
import com.fubowen.lepton.helper.IntentHelper.shareFile
import com.fubowen.lepton.helper.StorageHelper.getFileListOfDir
import com.fubowen.lepton.ui.container.children.download.recycler.DownloadAdapter
import com.fubowen.lepton.ui.container.children.download.recycler.DownloadSortedListAdapterCallback
import com.fubowen.lepton.ui.container.children.visited.recycler.OnItemClickListener
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

class DownloadFragment : Fragment() {

    private lateinit var binding: FragmentDownloadBinding
    private val viewModel: SiteConfigViewModel by activityViewModels()
    private lateinit var layoutManager: LinearLayoutManager
    private lateinit var sortedList: SortedList<FileConfig>
    private lateinit var adapter: DownloadAdapter

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        binding = FragmentDownloadBinding.inflate(inflater, container, false)
        layoutManager = LinearLayoutManager(context)
        binding.downloadRecycler.layoutManager = layoutManager

        adapter = DownloadAdapter()
        sortedList = SortedList(FileConfig::class.java, DownloadSortedListAdapterCallback(adapter))
        binding.downloadRecycler.adapter = adapter
        adapter.setDataSource(sortedList)

        CoroutineScope(Dispatchers.Main).launch {
            val downloadList = requireContext().getFileListOfDir(Environment.DIRECTORY_DOWNLOADS)
            sortedList.addAll(downloadList)
        }

//        adapter.setOnItemClickListener(object : OnItemClickListener {
//            override fun onClick(view: View) {
//                val position = layoutManager.getPosition(view)
//                val item = sortedList.get(position)
//                shareFile(item.fullName, item.path)
//            }
//
//            override fun onRemoveClick(view: View) {
//                val position = layoutManager.getPosition(view)
//                sortedList.removeItemAt(position)
//            }
//        })
        return binding.root
    }
}